<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">商品标题：</p>
      <el-input
        v-model="listQuery.title"
        size="small"
        placeholder="请输入商品标题"
        style="width: 200px;float:left"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        size="small"
        placeholder="请选择渠道"
        clearable
        class="filter-item"
        style="width: 250px;margin-left:2%"
        v-model="listQuery.channelType"
      >
        <el-option v-for="item in qudaoTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
      </el-select>
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;float:right"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="ID" min-width="50px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="楼层描述" min-width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.floorDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="配置商品个数" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.configNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图标" width="200px" align="center">
        <template slot-scope="scope">
          <!-- <span>{{ scope.row.phoneNumber }}</span> -->
          <img :src="scope.row.iconUrl" style="width:200px;height:100px" alt="">
        </template>
      </el-table-column>
      <el-table-column label="标题" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="副标题" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.subTitle }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.channelType=='APPLETS'?'小程序':scope.row.channelType=='CUSTOMER_APP'?'C端APP':scope.row.channelType=='SHOP_KEEPER'?'掌柜APP':scope.row.channelType=='OPERATE'?'运营管理平台':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type==="1"?"主题类":"图片类" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sortOrder }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"  
        width="250px"
        class-name="small-padding fixed-width"
      > 
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="danger"
            @click="handledelete(row)"
          >
            下架
          </el-button>
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            align="center"
            type="primary "
            @click="handleDetails(row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"  
      @pagination="getList"
    />
    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
      width="60%"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="150px"
        style="width: 600px; margin-left:150px;"
      >
        <el-form-item label="楼层描述：">
          <el-input v-model="temp.floorDesc" />
        </el-form-item>
        <el-form-item label="标题：">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="副标题：">
          <el-input v-model="temp.subTitle" />
        </el-form-item>
        <el-form-item label="渠道">
          <el-select
            size="small"
            placeholder="请选择渠道"
            clearable
            class="filter-item"
            style="width: 250px;margin-left:2%"
            v-model="temp.channelType"
          >
            <el-option v-for="item in qudaoTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="图标：">
          <el-input v-model="temp.iconUrl" />
        </el-form-item>
        <el-form-item label="">
          <el-upload
            class="avatar-uploader"
            action="http://10.0.0.123:10001/uploadImgUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :http-request="customRequest">
            <img style="width:100px;height:100px" v-if="temp.iconUrl" :src="temp.iconUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="配置商品个数：">
          <el-input v-model="temp.configNum" />
        </el-form-item>
        <el-form-item label="商品类型：">
          <el-select
              size="small"
              placeholder="请选择类型"
              clearable
              class="filter-item"
              style="width: 250px;"
              v-model="temp.type"
            >
              <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
            </el-select> 
        </el-form-item>
        <el-form-item label="楼层排序：">
          <el-input v-model="temp.sortOrder" />
        </el-form-item>
      </el-form>
      <el-table
        v-loading="listLoading"
        :data="zhutiList"
        ref="multipleTable"
        tooltip-effect="dark"
        size="small"
        v-if="temp.type=='1'"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-top:1%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column label="ID" min-width="50px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="recsId" width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.recommendId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="介绍" width="100px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.recommendDesc }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品" min-width="200px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.infoName }}</span>
            <!-- <img :src="scope.row.infoName" alt=""> -->
          </template>
        </el-table-column>
        <el-table-column label="图片" width="200px" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.imageUrl" style="width:100%;height:100%" alt="">
          </template>
        </el-table-column>
        <el-table-column label="排序" width="100px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sortOrder }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="temp.type=='1'"
        v-show="zhutiTotal > 0"
        :total="zhutiTotal"
        :page.sync="listQuery.pageNum"
        :limit.sync="listQuery.pageSize"
        @pagination="getzhutiListPage"
      />
      <el-table
        v-loading="listLoading"
        :data="imgList"
        :key="tableKey"
        ref="multipleTable1"
        tooltip-effect="dark"
        size="small"
        v-if="temp.type=='0'"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-top:1%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column label="ID" min-width="50px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="picsId" width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.picsId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="介绍" width="100px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.picsDesc }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品" min-width="200px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.infoName }}</span>
            <!-- <img :src="scope.row.infoName" alt=""> -->
          </template>
        </el-table-column>
        <el-table-column label="图片" width="200px" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.imageUrl" style="width:100%;height:100%" alt="">
          </template>
        </el-table-column>
        <el-table-column label="排序" width="100px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sortOrder }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="temp.type=='0'"
        v-show="imgTotal > 0"
        :total="imgTotal"
        :page.sync="listQuery.pageNum"
        :limit.sync="listQuery.pageSize"
        @pagination="getImgListPage"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="详情"
      :visible.sync="detailsVisible"
      append-to-body
      width="60%"
    >
    <el-table
      v-loading="listLoading"
      :data="detailList"
      :key="tableKey"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="ID" min-width="50px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="楼层描述" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.floorDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品" min-width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.infoName }}</span>
          <!-- <img :src="scope.row.infoName" alt=""> -->
        </template>
      </el-table-column>
      <el-table-column label="图片" width="200px" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.imageUrl" style="width:100%;height:100%" alt="">
        </template>
      </el-table-column>
      <el-table-column label="类型" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status==='1'?"主题类":"图片类" }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="detailTotal > 0"
      :total="detailTotal"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="handleDetails"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="detailsVisible = false">
        返回
      </el-button>
    </div>
    </el-dialog>
  </div>
</template>

<script>
import { getListPage,delOperation,addImg,getzhutiList,getImgList,getDetails,getFloorData,updateDataList,addDataList } from '@/api/operation'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 分页插件

const calendarTypeOptions = [
  { key: "0", display_name: '图片类' },
  { key: "1", display_name: '主题类' }
]
const qudaoTypeOptions = [
  { key: 'APPLETS', display_name: '小程序' },
  { key: 'CUSTOMER_APP', display_name: 'C端APP' },
  { key: 'SHOP_KEEPER', display_name: '掌柜APP' },
  { key: 'OPERATE', display_name: '运营管理平台' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
const calendarqudaoKeyValue = qudaoTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
export default {
  inject:["reload"],
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    qudaoFilter(type) {
      return calendarqudaoKeyValue[type]
    }
  },
  data() {
    return {
      detailsVisible:false,
      deptValue:'',
      tableKey: 0,
      list: null,
      zhutiList:null,
      imgList:null,
      total: 0,
      zhutiTotal:0,
      imgTotal:0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        channelType:'',
        sort: '+id',
        id:''
      },
      deps:[],
      info:'',
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        iconUrl:"",
        type:'',
        recommendId:[],
        picsId:[]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rowId:"",
      calendarTypeOptions,
      qudaoTypeOptions,
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      downloadLoading: false,
      liaUser: null,
      ids:[],
      idss:[],
      select:null,
      detailList:null,
      detailTotal:0,
      multipleSelection:[],
      SelectionList:[],
      SelectionList1:[],
      checkedList:[],
      idKey:'id',
      imgChecked:[],
      linshiList:[],
      linshiList1:[]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getFloor(){
      console.log(this.rowId)
      getFloorData(this.rowId).then(res=>{
        this.checkedList=res.recchecks
        this.imgChecked=res.picchecks
        console.log(this.checkedList)
      })
    },
    handleDetails(row){
      var params={
        type:row.type,
        floorId:row.floorId
      }
      getDetails(params).then(res=>{
        this.detailsVisible=true
        this.detailList=res.data
        this.detailTotal=res.recordsTotal
      })
    },
    handleAvatarSuccess(res, file) {
      this.temp.iconUrl = URL.createObjectURL(file.raw);
    },
    customRequest (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      this.saveFile(formData)
    },
    saveFile (formData) {
      addImg(formData).then(res=>{
        // this.imageUrl=res.data
        this.temp.iconUrl=res.data.filePath
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.temp.type)
      this.multipleSelection.forEach((item)=>{
        this.linshiList=item.recommendId
        this.linshiList1=item.picsId
      })
      if(this.temp.type==1){
        this.SelectionList.push(this.linshiList)
        this.SelectionList1=[]
      }else if(this.temp.type==0){
        this.SelectionList=[]
        this.SelectionList1.push(this.linshiList1)
      }
    },
    getList() {
      this.listLoading = true
      var params = {
        // pageConvert: true,
        pageNum: this.listQuery.pageNum,
        pageSize: this.listQuery.pageSize,
        // realName:this.listQuery.realName,
        // phoneNumber:this.listQuery.phoneNumber
        title: this.listQuery.title,
        channelType: this.listQuery.channelType
      }
      getListPage(params).then(response => {
        this.list = response.data
        this.total = response.recordsTotal
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 800)
      })
    },
    getzhutiListPage() {
      this.listLoading = true
      getzhutiList().then(response => {
        this.zhutiList = response.data   
        this.zhutiTotal = response.recordsTotal
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 800)
      })
    },
    getImgListPage() {
      this.listLoading = true
      getImgList().then(response => {
        this.imgList = response.data
        this.imgTotal = response.recordsTotal
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 800)
      })
    },
    
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {   
      this.temp = {
        id: undefined
      }
    },
    selectChecked () {
      const keyList = []
      this.checkedList.forEach(row => {
        keyList.push(row.picid)
      })
      console.log(this.zhutiList)
      for (let i = 0; i < this.zhutiList.length; i++) {
        if (keyList.indexOf(this.zhutiList[i].recommendId) >= 0) {
          // 设置选中，记住table组件需要使用ref="table"
          this.$refs.multipleTable.toggleRowSelection(this.zhutiList[i], true)
        }
      }
    },
    selectChecked1 () {
      const keyList1 = []
      this.imgChecked.forEach(row => {
        keyList1.push(row.picid)
      })
      console.log(this.imgList)
      for (let i = 0; i < this.imgList.length; i++) {
        if (keyList1.indexOf(this.imgList[i].picsId) >= 0) {
          // 设置选中，记住table组件需要使用ref="table"
          this.$refs.multipleTable1.toggleRowSelection(this.imgList[i], true)
        }
      }
    },
     handleUpdate(row) {
      this.rowId=row.id
      this.getFloor()
      this.getImgListPage()
      this.getzhutiListPage()
      setTimeout(() => {
        this.selectChecked()
        this.selectChecked1 ()
      }, 200)
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      console.log(this.temp.type)
        // this.temp.recommendId.push(this.linshiList)
        // this.temp.picsId.push(this.linshiList1)
        this.temp.recommendId=this.SelectionList
        this.temp.picsId=this.SelectionList1
      // tempData.timestamp = +new Date(tempData.timestamp)
      updateDataList(this.temp).then(() => {
        for (const v of this.list) {
          if (v.id === this.temp.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, this.temp)
            break
          }
        }
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
      this.reload()
    },
    handleCreate() {
      this.getImgListPage()
      this.getzhutiListPage()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.temp.recommendId=this.SelectionList
      this.temp.picsId=this.SelectionList1
      addDataList(this.temp).then(() => {
        this.list.unshift(this.temp)
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 2000
        }) 
      })
      this.reload()
    },
    handledelete(row){
        this.rowId=row.id
        this.$confirm('确定删除？ 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
            delOperation(this.rowId).then(res=>{
                this.$message({
                type: 'success',
                message: '删除成功!'
                });
             this.reload()
            })  
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
       
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>